package com.cmbchina.service2;

import com.cmbchina.service.BankService;
import com.cmbchina.service.ExchangeRateService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class PayService {
    @Autowired
    private BankService bankService;
    @Autowired
    private ExchangeRateService exchangeRateService;

    private static final Set<String> VALID_CURRENCY_SET = new HashSet<String>(){{
        add("CNY"); add("USD"); add("EUR"); add("JPY"); add("HKD");
    }};

    /**
     * 跨境支付
     * @param amount：原币种金额
     * @param originCurrency：原币种
     * @param targetCurrency：目标币种
     * @param recipientId：收款方ID
     */
    public void pay(BigDecimal amount, String originCurrency, String targetCurrency, Long recipientId){
        //校验支付金额合法性且大于0
        if(Objects.isNull(amount) || amount.compareTo(BigDecimal.ZERO) <= 0){
            throw new IllegalArgumentException("amount must be positive");
        }

        //币种参数合法性校验
        if(Objects.isNull(originCurrency) || Objects.isNull(targetCurrency)){
            throw new IllegalArgumentException("origin and target currency cannot be empty");
        }

        //校验付款币种和目标币种是系统支持的币种
        if(!VALID_CURRENCY_SET.contains(originCurrency.toUpperCase()) && !VALID_CURRENCY_SET.contains(targetCurrency.toUpperCase())){
            throw new IllegalArgumentException("invalid currency or not support for now");
        }

        if(originCurrency.equalsIgnoreCase(targetCurrency)){
            //同币种不需要转化，直接转账
            bankService.transfer(amount, targetCurrency, recipientId);
            return;
        }else{
            //不同币种，先获取汇率，计算金额，再转账
            BigDecimal exchangeRate = exchangeRateService.getRate(originCurrency, targetCurrency);
            if(Objects.isNull(exchangeRate) || (exchangeRate.compareTo(BigDecimal.ZERO) <= 0)){
                throw new RuntimeException("get exchange rate error");
            }
            BigDecimal targetAmount = amount.multiply(exchangeRate);
            bankService.transfer(targetAmount, targetCurrency, recipientId);
            return;
        }
    }
}

